package com.mz.ozy.activity.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.activity.me.PayPwdActivity;
import com.mz.ozy.activity.shop.PrivateDetailActivity;
import com.mz.ozy.adapter.BookHomeAdapter;
import com.mz.ozy.adapter.BoxBookAdapter;
import com.mz.ozy.adapter.MyBookAdapter;
import com.mz.ozy.adapter.PrivateCustomAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.ExchangeOrderBean;
import com.mz.ozy.bean.FamilyFeastBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.OnlineFamilyBean;
import com.mz.ozy.bean.OnlineListBean;
import com.mz.ozy.bean.OnlineOrderBean;
import com.mz.ozy.bean.OrderBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.PrivateCustomPresenter;
import com.mz.ozy.mvp.view.PrivateCustomContract;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.OptionsPickerUtils;
import com.mz.ozy.utils.PayManager;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.MyScrollView;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.PaySelectDialog;
import com.mz.ozy.widget.dialog.PrivateCardDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PrivateCustomActivity extends BaseActivity<PrivateCustomContract.View, PrivateCustomPresenter> implements PrivateCustomContract.View {
    @BindView(R.id.rl_private_relocation)
    RelativeLayout mRlReLocation;
    @BindView(R.id.recyclerviewOne)
    RecyclerView recyclerviewOne;
    @BindView(R.id.ll_no_data_One)
    LinearLayout llNoDataOne;
    @BindView(R.id.smartRefreshLayoutOne)
    SmartRefreshLayout smartRefreshLayoutOne;

    @BindView(R.id.scrollviewOne)
    MyScrollView scrollviewOne;
    @BindView(R.id.rv_private_box)
    RecyclerView mRvPrivateBox;

    @BindView(R.id.recyclerviewTwo)
    RecyclerView recyclerviewTwo;
    @BindView(R.id.ll_no_data_Two)
    LinearLayout llNoDataTwo;
    @BindView(R.id.smartRefreshLayoutTwo)
    SmartRefreshLayout smartRefreshLayoutTwo;

    @BindView(R.id.recyclerviewThree)
    RecyclerView recyclerviewThree;
    @BindView(R.id.ll_no_data_Three)
    LinearLayout llNoDataThree;
    @BindView(R.id.smartRefreshLayoutThree)
    SmartRefreshLayout smartRefreshLayoutThree;

    @BindView(R.id.tv_private_location)
    TextView mTvPrivateLocation;
    @BindView(R.id.tv_relocation_msg)
    TextView mTvRelocationMsg;
    @BindView(R.id.iv_image)
    ImageView mIvImage;
    @BindView(R.id.tv_private_title)
    TextView mTvPrivateTitle;
    @BindView(R.id.tv_desc1)
    TextView mTvPrivateDesc;
    @BindView(R.id.tv_price)
    TextView mTvPrivatePrice;
    @BindView(R.id.tv_address_name)
    TextView mTvAddressName;
    @BindView(R.id.tv_address)
    TextView mTvPrivateAddress;
    @BindView(R.id.tv_phone)
    TextView mTvPrivatePhone;
    @BindView(R.id.tv_full_reduction)
    TextView mTvReduction;
    @BindView(R.id.tv_book_date)
    TextView mTvBookDate;
    @BindView(R.id.tv_book_time)
    TextView mTvBookTime;
    @BindView(R.id.tv_book_num)
    TextView mTvBookNum;
    @BindView(R.id.et_input_name)
    EditText mEtInputName;
    @BindView(R.id.et_input_phone)
    EditText mEtInputPhone;
    @BindView(R.id.et_input_remark)
    EditText mEtInputRemark;
    @BindView(R.id.iv_man_select)
    ImageView mIvManSelect;
    @BindView(R.id.iv_woman_select)
    ImageView mIvWoManSelect;
    private int sex = 0;
    private int pageNo1 = 1;
    private int tag1 = 0;
    private int pageNo2 = 1;
    private int tag2 = 0;
    private PrivateCustomAdapter mAdapter;
    private BoxBookAdapter mBoxAdapter;
    private MyBookAdapter mBookAdapter;
    private BookHomeAdapter mHomeAdapter;
    private List<FamilyFeastBean.FamilyListBean> mBeanList = new ArrayList<>();
    private List<OnlineListBean.PageBean.PageItemsBean> mBeanList1 = new ArrayList<>();
    private List<OnlineListBean.PageBean.PageItemsBean> mBeanList2 = new ArrayList<>();
    private OnlineOrderBean orderBean;
    private PrivateCardDialog cardDialog;
    private List<ExchangeOrderBean.CardMapBean> mCardList;
    private ExchangeOrderBean.CardMapBean acListBean;
    private String mDate;
    private String dateFormat;
    private Date mDateObj;
    private String time;
    private String timeFormatStr;
    private OnlineFamilyBean.RoomListBean roomListBean;
    private String personNum;
    private OnlineFamilyBean onlineFamilyBean;
    private int payType;
    private PayManager mPayManager;
    private OnlineListBean.KtMapBean balance_map;
    private String user_balance = "0.00";
    private String user_integral = "0.00";
    private Calendar calToday;
    private String mPrice;
    private String mGname;
    private int mPostion = -1;
    private int mFamilyType = 0;
    private boolean reLocation = true;
    private boolean hasFamilyList = false;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    boolean isCountDown = countDownTime(1);
                    if (isCountDown) {
                        mBookAdapter.notifyDataSetChanged();
                        handler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
                }
                case 2: {
                    boolean isCountDown = countDownTime(2);
                    if (isCountDown) {
                        mHomeAdapter.notifyDataSetChanged();
                        handler.sendEmptyMessageDelayed(2, 1000);
                    }
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_custom);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);
        EventBus.getDefault().register(this);
        initTitle();
        setTitleBarMargin();
        final String title = getIntent().getStringExtra("title");
        tvCenterTitle.setText(title);
        mPayManager = new PayManager(this);
        calToday = Calendar.getInstance();
        calToday.setTime(new Date());
        initLocationState();
        iniFirstLayoutView();
        initSecondView();
        initThreeView();
        initFourView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        if ((event.getCode() == Constants.EventCode.WX_PAY_SUCCESS || event.getCode() == Constants.EventCode.ALIPAY_PAY_SUCCESS)) {
            ToastUtils.showToast("支付成功");
            if (mFamilyType == 0) {
                switchThreeLayout();
            } else {
                switchFourLayout();
            }
        }
        if (event.getCode() == Constants.EventCode.QUERY_ORDER_GID) {
            orderBean = (OnlineOrderBean) event.getData();
            switchTwoLayout();
        }
        if (event.getCode() == Constants.EventCode.REQUEST_BOOK_HOME) {
            switchFourLayout();
        }
        if (event.getCode() == Constants.EventCode.REQUEST_MY_BOOK) {
            switchThreeLayout();
        }
        if ((event.getCode() == Constants.EventCode.JUMP_PAY_PWD)) {
            startActivity(new Intent(this, PayPwdActivity.class));
        }
    }

    private void initLocationState() {
        if (LocationHelper.isIsLocate()) {
            mTvPrivateLocation.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(LocationHelper.getCity())) {
                mTvPrivateLocation.setText("未知");
            } else {
                mTvPrivateLocation.setText("您当前定位：" + LocationHelper.getCity() + LocationHelper.getmAddress() + LocationHelper.getmStreet());
            }
            if (reLocation) {
                if (mPresenter != null) {
                    mPresenter.geAssetsInfo(this, LocationHelper.getCity(), LocationHelper.getmAddress(), true);
                }
                reLocation = false;
            }
        } else {
            hasFamilyList = false;
            mTvPrivateLocation.setVisibility(View.GONE);
            mTvRelocationMsg.setText("定位不到您的所在位置，请确认定位功能正常");
            mRlReLocation.setVisibility(View.VISIBLE);
            smartRefreshLayoutOne.setVisibility(View.GONE);
        }
    }

    private void reLocationPrivate() {
        AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

                .onGranted(permissions -> {
                    LocationHelper.setOnLocationListener(new LocationHelper.onLocationListener() {
                        @Override
                        public void locationSuccess() {
                            initLocationState();
                        }
                    });
                    reLocation = true;
                    LocationHelper.initLocationOption();
                })
                .onDenied(permissions -> {
                    ToastUtils.showToast("为了功能正常使用，请您开启定位与存储权限");
                })
                .start();
    }

    private void iniFirstLayoutView() {
        recyclerviewOne.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new PrivateCustomAdapter(mBeanList);
        recyclerviewOne.setAdapter(mAdapter);
        smartRefreshLayoutOne.setEnableLoadmore(false);
        smartRefreshLayoutOne.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.geAssetsInfo(PrivateCustomActivity.this, LocationHelper.getCity(), LocationHelper.getmAddress(), true);
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final FamilyFeastBean.FamilyListBean productListBean = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view: {
                        Intent intent = new Intent(PrivateCustomActivity.this, PrivateDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        intent.putExtra("optype", 2);
                        startActivity(intent);
                        break;
                    }
                    case R.id.tv_order_home: {
                        Intent intent = new Intent(PrivateCustomActivity.this, PrivateDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        intent.putExtra("optype", 0);
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                    case R.id.tv_online_order: {
                        Intent intent = new Intent(PrivateCustomActivity.this, PrivateDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        intent.putExtra("optype", 1);
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
    }

    private void initThreeView() {
        recyclerviewTwo.setLayoutManager(new LinearLayoutManager(this));
        mBookAdapter = new MyBookAdapter(mBeanList1);
        recyclerviewTwo.setAdapter(mBookAdapter);
        smartRefreshLayoutTwo.setEnableAutoLoadmore(true);
//        smartRefreshLayout.autoRefresh();
        smartRefreshLayoutTwo.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                tag1 = 1;
                pageNo1 = pageNo1 + 1;
                mPresenter.queryOnlineOrder(PrivateCustomActivity.this, pageNo1 + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                refreshOnlineOrder();
            }
        });
        mBookAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final OnlineListBean.PageBean.PageItemsBean productListBean = mBookAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.tv_cancel_book: {
                        String message = "确定取消" + productListBean.getMealdata() + " " + Utils.formatTimeScopeStr(productListBean.getMealtime()) + "的" + productListBean.getBjname() + "的有机家宴?";
                        final BaseDialog dialog = new BaseDialog(PrivateCustomActivity.this, R.layout.dialog_private, Gravity.CENTER, true);
                        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText(message);
                        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("取消订座");
                        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.toggleDialog();
                            }
                        });
                        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.cancelBook(PrivateCustomActivity.this, productListBean.getId() + "");
                                dialog.toggleDialog();
                            }
                        });
                        dialog.toggleDialog();
                        break;
                    }
                    case R.id.tv_pay_book: {
                        String balance = "";
                        if (balance_map != null) {
                            if (!TextUtils.isEmpty(balance_map.getBalance())) {
                                balance = balance_map.getBalance();
                            }
                        }
                        showSportsHarmDialog(productListBean.getId() + "", productListBean.getPrice(), balance, 0, false);
                        break;
                    }
                    case R.id.ll_item_view: {
                        String balance = "";
                        if (balance_map != null) {
                            if (!TextUtils.isEmpty(balance_map.getBalance())) {
                                balance = balance_map.getBalance();
                            }
                        }
                        Intent intent = new Intent(PrivateCustomActivity.this, BookDetailActivity.class);
                        intent.putExtra("id", productListBean.getId() + "");
                        intent.putExtra("balance", balance);
                        intent.putExtra("price", productListBean.getPrice());
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
    }

    private void initFourView() {
        recyclerviewThree.setLayoutManager(new LinearLayoutManager(this));
        mHomeAdapter = new BookHomeAdapter(mBeanList2);
        recyclerviewThree.setAdapter(mHomeAdapter);
        smartRefreshLayoutThree.setEnableAutoLoadmore(true);
        smartRefreshLayoutThree.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                tag2 = 1;
                pageNo2 = pageNo2 + 1;
                mPresenter.queryHomeOrder(PrivateCustomActivity.this, "", pageNo2 + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (mPresenter == null) return;
                refreshHomeOrder();
            }
        });
        mHomeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final OnlineListBean.PageBean.PageItemsBean productListBean = mHomeAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.tv_cancel_book: {
                        String message = "确定取消当前有机家宴套餐?";
                        final BaseDialog dialog = new BaseDialog(PrivateCustomActivity.this, R.layout.dialog_private, Gravity.CENTER, true);
                        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText(message);
                        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("取消预定");
                        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.toggleDialog();
                            }
                        });
                        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.cancelBookHome(PrivateCustomActivity.this, productListBean.getTesq());
                                dialog.toggleDialog();
                            }
                        });
                        dialog.toggleDialog();
                        break;
                    }
                    case R.id.tv_pay_book: {
                        showSportsHarmDialog(productListBean.getId() + "", productListBean.getPrice(), user_balance, 1, false);
                        break;
                    }
                    case R.id.ll_item_view: {
                        break;
                    }
                }
            }
        });
    }

    private void refreshOnlineOrder() {
        tag1 = 0;
        pageNo1 = 1;
        mPresenter.queryOnlineOrder(PrivateCustomActivity.this, pageNo1 + "");
    }

    private void refreshHomeOrder() {
        tag2 = 0;
        pageNo2 = 1;
        mPresenter.queryHomeOrder(PrivateCustomActivity.this, "", pageNo2 + "");
    }

    private void initSecondView() {
        mRvPrivateBox.setLayoutManager(new GridLayoutManager(this, 3));
        mBoxAdapter = new BoxBookAdapter(null);
        mRvPrivateBox.setAdapter(mBoxAdapter);
        mBoxAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                roomListBean = mBoxAdapter.getItem(position);
                mBoxAdapter.setSelectPosition(position);
                personNum = "";
                mTvBookNum.setText("");
            }
        });
    }

    @OnClick({R.id.ll_tab_one, R.id.ll_tab_two, R.id.ll_tab_three, R.id.ll_tab_four,
            R.id.rl_full_reduction, R.id.rl_book_num, R.id.rl_book_date, R.id.rl_book_time,
            R.id.iv_man_select, R.id.iv_woman_select, R.id.tv_order_submit, R.id.tv_relocation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_relocation:
                reLocationPrivate();
                break;
            case R.id.ll_tab_one:
                switchOneLayout();
                break;
            case R.id.ll_tab_two:
                if (orderBean == null) {
                    ToastUtils.showToast("请先选择在线预定套餐");
                } else {
                    switchTwoLayout();
                }
                break;
            case R.id.ll_tab_three:
                switchThreeLayout();
                break;
            case R.id.ll_tab_four:
                switchFourLayout();
                break;
            case R.id.rl_full_reduction://地址
//                if (cardDialog != null) {
//                    cardDialog.toggleDialog();
//                } else {
//                    if (mCardList != null && mCardList.size() > 0) {
//                        showPopListView();
//                    }
//                }
                if (mCardList != null && mCardList.size() > 0) {
                    RedeemVoucherActivity1.go(this, mCardList, mPostion, mPrice, mGname);
                } else {
                    ToastUtils.showToast("暂无兑换券");
                }
                break;
            case R.id.rl_book_num:
                OptionsPickerUtils.showPersonNum(this, new OptionsPickerUtils.onSelectListener() {
                    @Override
                    public void onConfirm(Object object) {
                        personNum = (Integer) object + "";
                        mTvBookNum.setText(personNum);
                    }
                }, roomListBean.getMiniman(), roomListBean.getMaxman());
                break;
            case R.id.rl_book_date:
                OptionsPickerUtils.showDate(this, new OptionsPickerUtils.onDateListener() {
                    @Override
                    public void onConfirm(Object object, Date date) {
                        String tmpdate = (String) object;
                        final String[] dateArr = tmpdate.split(",");
                        dateFormat = dateArr[0];
                        mDate = dateArr[1];
                        mDateObj = date;
                        mTvBookDate.setText(dateFormat);
                        time = "";
                        timeFormatStr = "";
                        mTvBookTime.setText("");
                    }
                }, calToday);
                break;
            case R.id.rl_book_time:
                if (TextUtils.isEmpty(mDate)) {
                    ToastUtils.showToast("请先选择预订日期");
                    return;
                }
                if (TextUtils.isEmpty(onlineFamilyBean.getRestaurant_map().getStarttime()) || TextUtils.isEmpty(onlineFamilyBean.getRestaurant_map().getEndtime())) {
                    ToastUtils.showToast("餐厅暂未营业");
                    return;
                }
                String starttime = "";
                if (Utils.compareDateStr(mDateObj, calToday.getTime())) {
                    starttime = onlineFamilyBean.getRestaurant_map().getStarttime();
                } else {
                    final String hhMm = Utils.getHhMm(calToday.getTime().getTime());
                    String restaurantTime = onlineFamilyBean.getRestaurant_map().getStarttime();
                    final boolean isRestaurantTime = Utils.compareTimeStr(restaurantTime, hhMm);
                    if (isRestaurantTime) {
                        starttime = restaurantTime;
                    } else {
                        starttime = hhMm;
                    }
                }
                OptionsPickerUtils.showTime(this, new OptionsPickerUtils.onTimeListener() {
                    @Override
                    public void onConfirm(Object object, String timeStr) {
                        time = (String) object;
                        timeFormatStr = timeStr;
                        mTvBookTime.setText(time);
                    }
                }, starttime, onlineFamilyBean.getRestaurant_map().getEndtime());
                break;
            case R.id.iv_man_select:
                sex = 0;
                mIvManSelect.setImageResource(R.mipmap.icon_choose_press);
                mIvWoManSelect.setImageResource(R.mipmap.icon_choose_normal);
                break;
            case R.id.iv_woman_select:
                sex = 1;
                mIvManSelect.setImageResource(R.mipmap.icon_choose_normal);
                mIvWoManSelect.setImageResource(R.mipmap.icon_choose_press);
                break;
            case R.id.tv_order_submit:
                final String realName = mEtInputName.getText().toString().trim();
                final String phone = mEtInputPhone.getText().toString().trim();
                if (TextUtils.isEmpty(realName)) {
                    ToastUtils.showToast("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showToast("请输入联系电话");
                    return;
                }
                if (phone.length() < 11) {
                    ToastUtils.showToast("请输入合法的联系电话");
                    return;
                }
                if (TextUtils.isEmpty(personNum)) {
                    ToastUtils.showToast("请选择预订人数");
                    return;
                }
                if (TextUtils.isEmpty(mDate)) {
                    ToastUtils.showToast("请选择预订日期");
                    return;
                }
                if (TextUtils.isEmpty(time)) {
                    ToastUtils.showToast("请选择就餐时间");
                    return;
                }
                confirmOrder();
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002 && resultCode == RESULT_OK && data != null) {
            mPostion = data.getIntExtra("pos", 0);
            if (mPostion == -1) {
                acListBean = null;
                mTvReduction.setText(mCardList.size() + "张可用>");
                mTvReduction.setTextColor(ContextCompat.getColor(this, R.color.c_a5a5a5));
            } else {
                acListBean = mCardList.get(mPostion);
                mTvReduction.setText(acListBean.getCardname() + ">");
                mTvReduction.setTextColor(ContextCompat.getColor(this, R.color.c_73b21a));
            }
        }
    }

    private void switchFourLayout() {
        smartRefreshLayoutOne.setVisibility(View.GONE);
        mRlReLocation.setVisibility(View.GONE);
        scrollviewOne.setVisibility(View.GONE);
        smartRefreshLayoutTwo.setVisibility(View.GONE);
        smartRefreshLayoutThree.setVisibility(View.VISIBLE);
        refreshHomeOrder();
    }

    private void switchThreeLayout() {
        smartRefreshLayoutOne.setVisibility(View.GONE);
        mRlReLocation.setVisibility(View.GONE);
        scrollviewOne.setVisibility(View.GONE);
        smartRefreshLayoutThree.setVisibility(View.GONE);
        smartRefreshLayoutTwo.setVisibility(View.VISIBLE);
        refreshOnlineOrder();
    }

    private void switchOneLayout() {
        scrollviewOne.setVisibility(View.GONE);
        smartRefreshLayoutTwo.setVisibility(View.GONE);
        smartRefreshLayoutThree.setVisibility(View.GONE);
        if (hasFamilyList) {
            mRlReLocation.setVisibility(View.GONE);
            smartRefreshLayoutOne.setVisibility(View.VISIBLE);
        } else {
            mRlReLocation.setVisibility(View.VISIBLE);
            smartRefreshLayoutOne.setVisibility(View.GONE);
        }
    }

    private void switchTwoLayout() {
        smartRefreshLayoutOne.setVisibility(View.GONE);
        mRlReLocation.setVisibility(View.GONE);
        smartRefreshLayoutTwo.setVisibility(View.GONE);
        smartRefreshLayoutThree.setVisibility(View.GONE);
        scrollviewOne.setVisibility(View.VISIBLE);
        scrollviewOne.scrollTo(0, 0);
        mEtInputName.setText("");
        mEtInputPhone.setText("");
        mEtInputRemark.setText("");
        mBoxAdapter.setSelectPosition(0);
        mTvBookNum.setText("");
        mTvBookDate.setText("");
        mTvBookTime.setText("");
        mIvManSelect.setImageResource(R.mipmap.icon_choose_press);
        mIvWoManSelect.setImageResource(R.mipmap.icon_choose_normal);
        mPresenter.getInfo(this, LocationHelper.getCity(), LocationHelper.getmAddress(), orderBean.getId(), orderBean.getGid());
    }

    private void confirmOrder() {
        String message = "您确定预订了" + dateFormat + " " + timeFormatStr + "的" + roomListBean.getName() + "的有机家宴";
        final BaseDialog dialog = new BaseDialog(this, R.layout.dialog_private, Gravity.CENTER, true);
        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText(message);
        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("在线订座");
        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
            }
        });
        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String realName = mEtInputName.getText().toString().trim();
                final String phone = mEtInputPhone.getText().toString().trim();
                final String remark = mEtInputRemark.getText().toString().trim();
                String cardid = "";
                if (acListBean != null) {
                    cardid = acListBean.getId() + "";
                }
                mPresenter.onBookPrivate(PrivateCustomActivity.this, onlineFamilyBean.getId(),
                        onlineFamilyBean.getAttribute_id() + "", cardid, onlineFamilyBean.getRestaurant_map().getId() + "",
                        roomListBean.getId() + "", personNum + "", mDate, time, sex + "", realName, phone, remark);
                dialog.toggleDialog();
            }
        });
        dialog.toggleDialog();
    }

    private void showPopListView() {
        cardDialog = new PrivateCardDialog(this);
        cardDialog.setData(mCardList, mCardList.get(0).getId());
        cardDialog.setOnDialogListener(new PrivateCardDialog.onDialogListener() {
            @Override
            public void onConfirm(ExchangeOrderBean.CardMapBean item) {
                acListBean = item;
                mTvReduction.setText(item.getCardname() + ">");
            }
        });
        cardDialog.toggleDialog();
    }

    @Override
    public void geAssetsInfoSuccess(FamilyFeastBean bean) {
        hasFamilyList = true;
        mRlReLocation.setVisibility(View.GONE);
        smartRefreshLayoutOne.setVisibility(View.VISIBLE);
        smartRefreshLayoutOne.finishRefresh();
        final List<FamilyFeastBean.FamilyListBean> family_list = bean.getFamily_list();
        mBeanList.clear();
        if (family_list != null && family_list.size() > 0) {
            llNoDataOne.setVisibility(View.GONE);
        } else {
            llNoDataOne.setVisibility(View.VISIBLE);
        }
        if (family_list != null) {
            mBeanList.addAll(family_list);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        if ("1083".equals(bean.getRespCode())) {
            Toast toast = new Toast(this);
            toast.setGravity(Gravity.CENTER, 0, 0);
            final View toastView = View.inflate(this, R.layout.toast_private_view, null);
            TextView tvPrivateMsg = toastView.findViewById(R.id.tv_private_msg);
            tvPrivateMsg.setText("距离就餐时间小于1小时不可取消,请联系客服");
            toast.setView(toastView);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.show();
        } else if ("1077".equals(bean.getRespCode())) {
            Toast.makeText(this, bean.getRespMsg(), Toast.LENGTH_SHORT).show();
            hasFamilyList = false;
            mTvRelocationMsg.setText("当前所在地区未开通");
            mRlReLocation.setVisibility(View.VISIBLE);
            smartRefreshLayoutOne.setVisibility(View.GONE);
        } else {
            super.handleFailResponse(bean);
            smartRefreshLayoutOne.finishRefresh();
            if (Constants.TransCode.TransCode10094.equals(bean.getTransCode())) {
                switchThreeLayout();
            }
        }
    }

    @Override
    public void getInfo(OnlineFamilyBean bean) {
        onlineFamilyBean = bean;
        mTvPrivateTitle.setText(bean.getName());
        mTvPrivateDesc.setText(bean.getTradname());
        String imgUrl = "";
        if (!TextUtils.isEmpty(bean.getImg_zt())) {
            final String[] img_arr = bean.getImg_zt().trim().split(",");
            if (img_arr.length > 0) {
                imgUrl = img_arr[0];
            }
        }
        GlideUtils.loadRoundImg(this, mIvImage, imgUrl, R.mipmap.default_foods_icon, 4);
        mPrice = bean.getPrice();
        mGname = bean.getGname();
        mTvPrivatePrice.setText("¥" + bean.getPrice());
        mTvAddressName.setText(bean.getRestaurant_map().getName());
        mTvPrivateAddress.setText("地址：" + bean.getRestaurant_map().getAddress());
        mTvPrivatePhone.setText(bean.getRestaurant_map().getPhone());

        final List<OnlineFamilyBean.RoomListBean> room_list = bean.getRoom_list();
        if (room_list != null && room_list.size() > 0) {
            roomListBean = room_list.get(0);
            mBoxAdapter.setNewData(room_list);
        }

        final List<ExchangeOrderBean.CardMapBean> cardlist = bean.getCard_list();
        if (cardlist != null && cardlist.size() > 0) {
            this.mCardList = cardlist;
            mPostion = 0;
            acListBean = mCardList.get(0);
            mTvReduction.setText(acListBean.getCardname() + ">");
            mTvReduction.setTextColor(ContextCompat.getColor(this, R.color.c_73b21a));
        } else {
            mTvReduction.setText("无可用卡券>");
        }
//        if (tag == 0) {
//            smartRefreshLayoutOne.setLoadmoreFinished(false);
//            smartRefreshLayoutOne.finishRefresh();
//            mBeanList.clear();
//            if (bean.getPage().getPageItems().size() == 0) {
//                llNoDataOne.setVisibility(View.VISIBLE);
//            } else {
//                llNoDataOne.setVisibility(View.GONE);
//            }
//        } else if (tag == 1) {
//            smartRefreshLayoutOne.finishLoadmore();
//        }
//        mBeanList.addAll(bean.getPage().getPageItems());
//        mAdapter.notifyDataSetChanged();
//        if (bean.getPage().getPageItems().size() == 0 || bean.getPage().getPageSize() * bean.getPage().getPageNumber() >= bean.getPage().getPageTotle()) {
//            smartRefreshLayoutOne.setLoadmoreFinished(true);//将不会再次触发加载更多事件
//        }
    }

    @Override
    public void onBookPrivateSuccess(OrderBean orderBean) {
        String balance = "";
        if (onlineFamilyBean.getBalance_map() != null) {
            if (!TextUtils.isEmpty(onlineFamilyBean.getBalance_map().getBalance())) {
                balance = onlineFamilyBean.getBalance_map().getBalance();
            }
        }
        showSportsHarmDialog(orderBean.getOrderId(), onlineFamilyBean.getPrice(), balance, 0, true);
    }

    private void showSportsHarmDialog(final String orderId, String price, final String balance, final int familyType, final boolean online) {
        mFamilyType = familyType;
        if (mFamilyType == 0) {
            if (acListBean != null) {
                price = "0.00";
            }
        }
        PaySelectDialog mSportsHarmDialog = new PaySelectDialog(this, 2);
        mSportsHarmDialog.setData(price, balance);
        mSportsHarmDialog.setOnDialogListener(new PaySelectDialog.onDialogListener() {
            @Override
            public void onConfirm(int type, String payPwd) {
                payType = type;
                mPresenter.onPay(PrivateCustomActivity.this, orderId, type + "", payPwd, familyType);
            }

            @Override
            public void onCancel() {
                if (online) {
                    switchThreeLayout();
                }
            }
        });
        mSportsHarmDialog.toggleDialog();
        acListBean = null;
    }

    private boolean setCountDownTime(String data, int type) {
        boolean isCountDown = false;
        List<OnlineListBean.PageBean.PageItemsBean> pageItems = null;
        if (type == 1) {
            pageItems = mBeanList1;
        } else {
            pageItems = mBeanList2;
        }
        if (pageItems.size() > 0) {
            for (OnlineListBean.PageBean.PageItemsBean pageItemBean : pageItems) {
                if (pageItemBean.getState() == 0) {
                    if (startCountDown(pageItemBean, data)) {
                        isCountDown = true;
                    }
                }
            }
        }
        return isCountDown;
    }

    private boolean startCountDown(OnlineListBean.PageBean.PageItemsBean pageItemBean, String created) {
        try {
            String compareDate = pageItemBean.getEndtime();
            final long nowInt = Utils.parseDateIntTime(created);
            final long endtimeInt = Utils.parseDateIntTime(compareDate);

            if (endtimeInt > nowInt) {
                final long spaceTimeInt = (endtimeInt - nowInt) / 1000;
                pageItemBean.setSpaceTime(spaceTimeInt);
                return true;
            } else {
                pageItemBean.setTimeOut(true);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean countDownTime(int type) {
        boolean isCountDown = false;
        boolean reStart = false;
        List<OnlineListBean.PageBean.PageItemsBean> pageItems = null;
        if (type == 1) {
            pageItems = mBeanList1;
        } else {
            pageItems = mBeanList2;
        }
        if (pageItems.size() > 0) {
            for (OnlineListBean.PageBean.PageItemsBean pageItemBean : pageItems) {
                if (pageItemBean.getState() == 0) {
                    pageItemBean.setSpaceTime(pageItemBean.getSpaceTime() - 1);
                    if (pageItemBean.getSpaceTime() > 0) {
                        isCountDown = true;
                    } else {
                        pageItemBean.setTimeOut(true);
                        reStart = true;
                    }
                }
            }

        }
        if (reStart) {
            isCountDown = false;
        }
        return isCountDown;
    }

    @Override
    public void queryOnlineOrderSuccess(OnlineListBean bean) {
        balance_map = bean.getBalance_map();
        if (tag1 == 0) {
            smartRefreshLayoutTwo.setLoadmoreFinished(false);
            smartRefreshLayoutTwo.finishRefresh();
            mBeanList1.clear();
            if (bean.getPage().getPageItems().size() == 0) {
                llNoDataTwo.setVisibility(View.VISIBLE);
            } else {
                llNoDataTwo.setVisibility(View.GONE);
            }
        } else if (tag1 == 1) {
            smartRefreshLayoutTwo.finishLoadmore();
        }
        mBeanList1.addAll(bean.getPage().getPageItems());
        if (!TextUtils.isEmpty(bean.getDate())) {
            boolean isCountDown = setCountDownTime(bean.getDate(), 1);
            handler.removeMessages(1);
            if (isCountDown) {
                handler.sendEmptyMessageDelayed(1, 1000);
            }
        }
        mBookAdapter.notifyDataSetChanged();
        if (bean.getPage().getPageItems().size() == 0 || bean.getPage().getPageSize() * bean.getPage().getPageNumber() >= bean.getPage().getPageTotle()) {
            smartRefreshLayoutTwo.setLoadmoreFinished(true);//将不会再次触发加载更多事件
        }
    }

    @Override
    public void queryHomeOrderSuccess(OnlineListBean bean) {
        if (!TextUtils.isEmpty(bean.getUser_balance())) {
            user_balance = bean.getUser_balance();
        }
        if (!TextUtils.isEmpty(bean.getUser_integral())) {
            user_integral = bean.getUser_integral();
        }
        if (tag2 == 0) {
            smartRefreshLayoutThree.setLoadmoreFinished(false);
            smartRefreshLayoutThree.finishRefresh();
            mBeanList2.clear();
            if (bean.getPage().getPageItems().size() == 0) {
                llNoDataThree.setVisibility(View.VISIBLE);
            } else {
                llNoDataThree.setVisibility(View.GONE);
            }
        } else if (tag2 == 1) {
            smartRefreshLayoutThree.finishLoadmore();
        }
        mBeanList2.addAll(bean.getPage().getPageItems());
        if (!TextUtils.isEmpty(bean.getDate())) {
            boolean isCountDown = setCountDownTime(bean.getDate(), 2);
            handler.removeMessages(2);
            if (isCountDown) {
                handler.sendEmptyMessageDelayed(2, 1000);
            }
        }
        mHomeAdapter.notifyDataSetChanged();
        if (bean.getPage().getPageItems().size() == 0 || bean.getPage().getPageSize() * bean.getPage().getPageNumber() >= bean.getPage().getPageTotle()) {
            smartRefreshLayoutThree.setLoadmoreFinished(true);//将不会再次触发加载更多事件
        }
    }

    @Override
    public void cancelBookSuccess(OnlineListBean orderBean) {
        refreshOnlineOrder();
    }

    @Override
    public void cancelBookHomeSuccess(OnlineListBean orderBean) {
        refreshHomeOrder();
    }

    @Override
    public void onPayError(String s) {
        ToastUtils.showToast("支付失败");
    }

    @Override
    public void onPaySuccess(JSONObject orderBean) {
        if (payType == 0) { //余额支付
            ToastUtils.showToast("支付成功");
            if (mFamilyType == 0) {
                switchThreeLayout();
            } else {
                switchFourLayout();
            }
        } else if (payType == 2) {  //微信支付
            mPayManager.handleWxPay(orderBean);
        } else if (payType == 1) {  //支付宝支付
            mPayManager.handleAliPay(orderBean.optString("zfb"));
        }
    }

}
